package com.example.repository;

import com.example.model.OperationLog;
import com.example.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface OperationLogRepository extends JpaRepository<OperationLog, Long> {
    
    // 根据用户查找日志
    Page<OperationLog> findByUser(User user, Pageable pageable);
    
    // 根据用户名查找日志
    Page<OperationLog> findByUsername(String username, Pageable pageable);
    
    // 根据操作类型查找日志
    Page<OperationLog> findByOperationType(OperationLog.OperationType operationType, Pageable pageable);
    
    // 根据模块查找日志
    Page<OperationLog> findByModule(String module, Pageable pageable);
    
    // 根据成功状态查找日志
    Page<OperationLog> findBySuccess(Boolean success, Pageable pageable);
    
    // 根据时间范围查找日志
    @Query("SELECT ol FROM OperationLog ol WHERE ol.createdAt BETWEEN :startTime AND :endTime")
    List<OperationLog> findByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
    
    // 查找今日日志
    @Query("SELECT ol FROM OperationLog ol WHERE ol.createdAt >= :startOfDay AND ol.createdAt < :endOfDay")
    List<OperationLog> findTodayLogs(@Param("startOfDay") LocalDateTime startOfDay, @Param("endOfDay") LocalDateTime endOfDay);

    // 查找失败的操作日志
    List<OperationLog> findBySuccessFalseOrderByCreatedAtDesc();

    // 统计各操作类型数量
    @Query("SELECT ol.operationType, COUNT(ol) FROM OperationLog ol GROUP BY ol.operationType")
    List<Object[]> countByOperationType();

    // 统计各模块操作数量
    @Query("SELECT ol.module, COUNT(ol) FROM OperationLog ol GROUP BY ol.module")
    List<Object[]> countByModule();

    // 统计各用户操作数量
    @Query("SELECT ol.username, COUNT(ol) FROM OperationLog ol GROUP BY ol.username")
    List<Object[]> countByUsername();

    // 统计成功失败操作数量
    @Query("SELECT ol.success, COUNT(ol) FROM OperationLog ol GROUP BY ol.success")
    List<Object[]> countBySuccess();

    // 查找最近的登录日志
    @Query("SELECT ol FROM OperationLog ol WHERE ol.operationType = 'LOGIN' ORDER BY ol.createdAt DESC")
    List<OperationLog> findRecentLoginLogs(Pageable pageable);

    // 统计用户今日操作次数
    @Query("SELECT COUNT(ol) FROM OperationLog ol WHERE ol.username = :username AND ol.createdAt >= :startOfDay AND ol.createdAt < :endOfDay")
    Long countTodayOperationsByUsername(@Param("username") String username, @Param("startOfDay") LocalDateTime startOfDay, @Param("endOfDay") LocalDateTime endOfDay);
}
